#!/usr/bin/env python3
# SiliconCompiler Replay
# Design: {{ design }}
# Jobname: {{ jobname }}
# Date: {{ date }}

import base64
import os.path
import tarfile
import sys

from io import BytesIO

from siliconcompiler import Project
from siliconcompiler.utils.collect import collectiondir

# Input files as a tarball encoded as base64
INPUT_FILES = \{% for line in src_file %}
    "{{ line }}"{% if not loop.last %} \{% endif %}{% endfor %}


if __name__ == "__main__":
    project = Project.from_manifest(os.path.join(os.path.dirname(__file__), "sc_manifest.json"))

    class CLIProject(Project):
        def __init__(self):
            super().__init__()
            self._add_commandline_argument("check_files", "bool", "Do not run, just check files")

    cli_proj = CLIProject.create_cmdline(
        progname="{{ design }}",
        description="Replay script for {{ design }} / {{ jobname }}",
        switchlist=[
            "-builddir",
            "-cachedir",
            "-jobname",
            "-to",
            "-from",
            "-novercheck",
            "-continue",
            "-check_files"
        ])

    # Extract input files
    with BytesIO(base64.b64decode(INPUT_FILES.encode())) as fd:
        with tarfile.open(fileobj=fd, mode='r:gz') as tar:
            tar.extractall(path=collectiondir(project))

    if cli_proj.get("cmdarg", "check_files"):
        if project.check_filepaths():
            sys.exit(0)
        else:
            sys.exit(1)

    # Run
    project.run()

    # Report summary
    project.summary()
